﻿using Dilon.Core;
using Furion;
using Furion.DatabaseAccessor;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;

namespace Dilon.EntityFramework.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            #region 配置sqlsuagr
            List<ConnectionConfig> connectConfigList = new List<ConnectionConfig>();
            connectConfigList.Add(new ConnectionConfig
            {
                ConnectionString = $"{App.Configuration["ConnectionStrings:DefaultConnection"]}",
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
                ConfigId = "0"
            });
            //connectConfigList.Add(new ConnectionConfig
            //{
            //    ConnectionString = $"{App.Configuration["ConnectionStrings:MultiTenantConnection"]}",
            //    DbType = DbType.SqlServer,
            //    IsAutoCloseConnection = true,
            //    InitKeyType = InitKeyType.Attribute,
            //    ConfigId = "1"
            //});

            services.AddSqlSugar(connectConfigList.ToArray()
                , db =>
                {
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                };
                    //配置多租户全局过滤器
                    db.QueryFilter.Add(new TableFilterItem<SysUser>(it => it.TenantId ==  long.Parse(GetTenantId().ToString())));
                    db.QueryFilter.Add(new TableFilterItem<SysOrg>(it => it.TenantId == long.Parse(GetTenantId().ToString())));
                    db.QueryFilter.Add(new TableFilterItem<SysPos>(it => it.TenantId == long.Parse(GetTenantId().ToString())));
                    db.QueryFilter.Add(new TableFilterItem<SysRole>(it => it.TenantId == long.Parse(GetTenantId().ToString())));
                    db.QueryFilter.Add(new TableFilterItem<SysPos>(it => it.TenantId == long.Parse(GetTenantId().ToString())));
                });
            #endregion
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            
        }
       
        private object GetTenantId()
        {
            if (App.User == null) return null;
            return App.User.FindFirst(ClaimConst.TENANT_ID)?.Value;
        }
    }
}